package io.uouo.wechatbot.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import io.uouo.wechatbot.gp.model.GPModel;
import io.uouo.wechatbot.gp.model.HQDetail;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * http://ig507.com/index.html
 * @author wangwei
 * @date 2021/6/30
 */
public class IG507Util {
    public static final String licence = "9F1DB302-A18D-70BB-05DE-F0A78FAFBD0D";

    private static final Map<String, List<GPModel>> GP_MODEL_MAP = new HashMap<>();
    private static final List<GPModel> GP_MODELS = new ArrayList<>();
    public static void initGPALL(){
        String s = HttpUtil.get("http://ig507.com/data/base/gplist?licence=" + licence);
        List<GPModel> gpModels = JSON.parseArray(s, GPModel.class);
        Map<String, List<GPModel>> collect = gpModels.stream().collect(Collectors.groupingBy(t-> StringUtils.trimAllWhitespace(t.getMc())));
        GP_MODELS.addAll(gpModels);
        GP_MODEL_MAP.putAll(collect);
    }

    public static HQDetail getDetail(String dm,String mc){
        String s = HttpUtil.get("http://ig507.com/data/time/real/" + dm + "?licence=" + licence);
        HQDetail hqDetail = JSON.parseObject(s, HQDetail.class);
        hqDetail.setName(mc);
        return hqDetail;
    }

    public static HQDetail getDetailByMc(String mc){
        try {
            List<GPModel> gpModels = GP_MODEL_MAP.get(StringUtils.trimAllWhitespace(mc));
            if(gpModels!=null){
                String dm = gpModels.get(0).getDm();
                return getDetail(dm,mc);
            }else {
                Optional<GPModel> first =
                        GP_MODELS.parallelStream().filter(t ->
                                StringUtils.trimAllWhitespace(t.getMc()).contains(StringUtils.trimAllWhitespace(mc)))
                                .findFirst();
                if(first.isPresent()){
                    return getDetail(first.get().getDm(),mc);
                }
            }
            return getDetail(StringUtils.trimAllWhitespace(mc),mc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        initGPALL();
        HQDetail detail = getDetailByMc("格力");
        System.out.println(JSON.toJSONString(detail));
    }

}
